package com.ruoyi.client.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.client.pojo.form.UserLoginForm;
import com.ruoyi.client.pojo.form.UserRegisterForm;
import com.ruoyi.client.pojo.vo.UserLoginVo;
import com.ruoyi.client.pojo.vo.UserRegisterVo;
import com.ruoyi.client.pojo.vo.UserVo;
import com.ruoyi.client.service.IClientUserService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @Author：HuaQP
 * @Date：2024/4/23
 */
@Anonymous  //接口允许匿名访问
@RestController
@RequestMapping("/user")
public class ClientUserController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(ClientUserController.class);
    @Resource
    private IClientUserService userService;
    // 用户登录
    @PostMapping("/login")
    public AjaxResult login(@RequestBody UserLoginForm form) {
        // 调用服务层，用户登录验证
        UserVo userVo = userService.login(form);
        Long userId = userVo.getId();
        // 用户登录 sa-token 认证
        StpUtil.login(userId);
        // 获取登录用户的Token
        String token = StpUtil.getTokenValue();
        // 封装用户登录后返回数据
        UserLoginVo userLoginVo = new UserLoginVo();
        userLoginVo.setUser(userVo);
        userLoginVo.setToken(token);
        // 接口返回
        return AjaxResult.success(userLoginVo);
    }

    // 用户注册
    @PostMapping("/register")
    public AjaxResult register(@RequestBody @Valid UserRegisterForm form){
        // 调用服务层
        UserVo userVo = userService.register(form);
        // 封装数据返回
        UserRegisterVo userRegisterVo = new UserRegisterVo();
        userRegisterVo.setUser(userVo);
        return AjaxResult.success(userRegisterVo);
    }

    // 用户详情

    @GetMapping("/detail")
    public AjaxResult detail(@RequestParam Long id){
        // 登录验证
        StpUtil.checkLogin();
        logger.info("用户Id:" + StpUtil.getLoginIdAsInt() +  "/Token:" + StpUtil.getTokenValue());
        // 调用服务层
        UserVo userVo = userService.selectById(id);
        // 数据返回
        return AjaxResult.success(userVo);
    }

    @GetMapping("/logout")
    public AjaxResult logout(){
        StpUtil.logout();
        return AjaxResult.success();
    }
}
